import wave
from pyaudio import PyAudio, paInt16
import time
framerate = 16000  # 采样率
num_samples = 2000  # 采样点
channels = 1  # 声道
sampwidth = 2  # 采样宽度2bytes
FILEPATH = 'speech.wav'

#主界面ip，port
port=('192.168.1.113',8881)


s = '的、了、呢、吧、啊、嗯、话、哪、啦、嗨'.split('、')
a = dict()
for i in s:
    a[i] = 0

def trans(data):
    global  a
    for i in list(a.keys()):
        a[i] = a[i]+data.count(i)
    return a


def save_wave_file(filepath, data):
    wf = wave.open(filepath, 'wb')
    wf.setnchannels(channels)
    wf.setsampwidth(sampwidth)
    wf.setframerate(framerate)
    wf.writeframes(b''.join(data))
    wf.close()


# 录音
def my_record():
    pa = PyAudio()
    # 打开一个新的音频stream
    stream = pa.open(format=paInt16, channels=channels,
                     rate=framerate, input=True, frames_per_buffer=num_samples)
    my_buf = []  # 存放录音数据

    t = time.time()


    while time.time() < t + 4:  # 设置录音时间（秒）
        # 循环read，每次read 2000frames
        string_audio_data = stream.read(num_samples)
        my_buf.append(string_audio_data)

    save_wave_file(FILEPATH, my_buf)
    stream.close()


import requests
import base64  # 百度语音要求对本地语音二进制数据进行base64编码

# 组装url获取token，详见文档
base_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"
APIKey = "GAOVeyeUiUI19TRqIdLbyX84"
SecretKey = "Tf4VwuSD4Ee73HKKWXlUs1mg0hmPn1cE"

HOST = base_url % (APIKey, SecretKey)


def getToken(host):
    res = requests.post(host)
    return res.json()['access_token']


def get_audio(file):
    with open(file, 'rb') as f:
        data = f.read()
    return data


# 传入语音二进制数据，token
# dev_pid为百度语音识别提供的几种语言选择
def speech2text(speech_data, token, dev_pid=1537):
    FORMAT = 'wav'
    RATE = '16000'
    CHANNEL = 1
    CUID = '********'
    SPEECH = base64.b64encode(speech_data).decode('utf-8')

    data = {
        'format': FORMAT,
        'rate': RATE,
        'channel': CHANNEL,
        'cuid': CUID,
        'len': len(speech_data),
        'speech': SPEECH,
        'token': token,
        'dev_pid': dev_pid
    }
    url = 'https://vop.baidu.com/server_api'
    headers = {'Content-Type': 'application/json'}
    # r=requests.post(url,data=json.dumps(data),headers=headers)

    r = requests.post(url, json=data, headers=headers)

    Result = r.json()
    print(Result)
    if 'result' in Result:
        return Result['result'][0]
    else:
        return Result

def get():
    my_record()
    TOKEN = getToken(HOST)
    speech = get_audio(FILEPATH)
    result = speech2text(speech, TOKEN, 1537)
    print(result)
    result = str(trans(str(result)))
    return  result

import socket
if __name__ == '__main__':
    s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    s.settimeout(4)
    ss=True
    while 1:
        try:
            s.sendto('we -start'.encode('utf-8'),port)

            m=s.recv(1024)
            print(1)
            if m.decode('utf-8')=='start1':
                while ss:
                    result=get()
                    s.sendto(result.encode('utf-8'),port)
                    try:
                        m=s.recv(1024).decode('utf-8')
                        if m=='stop':
                            ss=False
                    except:
                        print('断开连接')
        except:
            print('no receve')

